package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/prometheus/common/log"
	"net/http"
	"remote_cmd/models"
	"strings"

	"remote_cmd/result"
	"remote_cmd/utils"

	beego "github.com/beego/beego/v2/server/web"
)

type DirController struct {
	beego.Controller
}

func (c *DirController) Dirs() {
	ip := c.GetString("ip")
	if !utils.IsValidIP(ip) {
		result.HttpResponse(http.StatusBadRequest, []byte("Invalid IP"), c.Ctx)
		return
	}
	linux, ok := models.LinuxCache[ip]
	if !ok {
		result.HttpResponse(http.StatusUnauthorized, []byte(fmt.Sprintf("ip[%s] not logged in", ip)), c.Ctx)
		return
	}
	dirs, err := linux.Exec(fmt.Sprintf("ls -alF %s", linux.Pkg))
	if err != nil {
		result.HttpResponse(http.StatusInternalServerError, []byte(err.Error()), c.Ctx)
		return
	}
	dirFiles := strings.Split(string(dirs), "\n")
	dirFiles = dirFiles[3 : len(dirFiles)-1]
	var resultMap = make(map[string]interface{})
	resultMap["pwd"] = linux.Pkg
	resultMap["ls"] = utils.HandlerFilesName(utils.DelSpace(dirFiles))
	resByte, err := json.Marshal(resultMap)
	if err != nil {
		log.Errorf(fmt.Sprintf("json marshal error:%v", err))
		result.HttpResponse(http.StatusInternalServerError, []byte(err.Error()), c.Ctx)
		return
	}
	result.HttpResponse(http.StatusOK, resByte, c.Ctx)
}

func (c *DirController) ChangeDir() {
	var dirChange models.DirChange
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dirChange)
	if err != nil {
		result.HttpResponse(http.StatusBadRequest, []byte(err.Error()), c.Ctx)
		return
	}
	linux, ok := models.LinuxCache[dirChange.Ip]
	if !ok {
		result.HttpResponse(http.StatusUnauthorized, []byte(fmt.Sprintf("ip[%s] not logged in", dirChange.Ip)), c.Ctx)
		return
	}
	cmd := fmt.Sprintf("cd %s", dirChange.Dir)
	_, err = linux.Exec(cmd)
	if err != nil {
		result.HttpResponse(http.StatusBadRequest, []byte(err.Error()), c.Ctx)
		return
	}
	result.HttpResponse(http.StatusOK, []byte("change dir success"), c.Ctx)
}
